package com.fly.fox.gw.zuul;

import com.fly.fox.common.FoxConstants;
import com.fly.fox.common.context.FoxContext;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

public class ContextInitFilter extends ZuulFilter {
	private static final Logger logger = LoggerFactory.getLogger(ContextInitFilter.class);

	@Resource
	Tracer tracer;

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		String traceId=tracer.getCurrentSpan().traceIdString();
		String spanId=Span.idToHex(tracer.getCurrentSpan().getSpanId());

		MDC.put(FoxConstants.TRACE_ID,traceId);
		MDC.put(FoxConstants.SPAN_ID,spanId);
		logger.debug("初始化请求上下文{}",tracer.getCurrentSpan());
		FoxContext.putToCurrentContext(FoxConstants.TRACE_ID,tracer.getCurrentSpan().traceIdString());
		FoxContext.putToCurrentContext(FoxConstants.SPAN_ID,Span.idToHex(tracer.getCurrentSpan().getSpanId()));
		return null;
	}
}
